#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
企业管理

"""

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
from datetime import datetime

from django.shortcuts import render, reverse, redirect
from django.contrib.auth import get_user
from django.contrib.auth.decorators import login_required, permission_required

from django.http import HttpResponse, HttpResponseRedirect

from smAdmin.models import SmerpErpinfo, SmerpAccount, SmerpBrand, SmerpProduct, SmerpMaterial, SmerpSmcodeOrder, SmerpSmcode, CHECK_STATUS_CHOICES

from smAdmin.jqgrid import JqGrid

import logging

# Get an instance of a logger
logger = logging.getLogger('smAdmin')


# -------------企业列表------------------
class SmerpErpinfoGrid(JqGrid):
	model = SmerpErpinfo  # could also be a queryset
	pager_id = "erpinfo-grid-pager"
	fields = ['id',
			  'full_name',
			  'check_status',
			  'smerpaccount__email',
			  # 'organization_code',
			  # 'registration_no',
			  'representative',
			  # 'scope_normal',
			  # 'scope_special',
			  # 'staff_num',
			  # 'licence_img',
			  'manager',
			  'manager_phone',
			  # 'manager_id_card_no',
			  # 'manager_id_card_img',
			  # 'create_time',
			  'myac'
			  ]  # optional

	url = '/smAdmin/enterprise/erpinfo_list'
	editurl = '/smAdmin/enterprise/erpinfo_edit'
	caption = u'企业列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'create_time': {
			"label": u"创建时间",
			"sorttype": 'date',

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'width': 100
		},
		'smerpaccount__email': {
			"label": u"账号",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},

		'full_name': {
			"label": u"企业全称",

			"sortable": False,
			"sorttype": 'string',

			"editable": True,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'width': 100
		},
		'check_status': {
			"label": u"审核状态",
			"sorttype": 'integer',

			"editable": True,
			"edittype": 'select',
			"editoptions": {"value": "0:未提交;1:待审核;2:通过;3:驳回"},

			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "0:未提交;1:待审核;2:通过;3:驳回"},
			"sortable": False,
			'width': 100
		},
		# 'organization_code': {
		# 	"label": u"组织机构代码",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },
		# 'registration_no': {
		# 	"label": u"工商执照注册号",
		# 	"sortable": False,
		# 	"hidden": True,z
		# 	'width': 100
		# },
		'representative': {
			"label": u"法人",
			"sortable": False,
			"search": False,
			'width': 100
		},
		# 'scope_normal': {
		# 	"label": u"一般经营范围",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },
		# 'scope_special': {
		# 	"label": u"前置许可经营范围",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },
		# 'staff_num': {
		# 	"label": u"企业规模",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },
		# 'licence_img': {
		# 	"label": u"营业执照",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },

		'manager': {
			"label": u"管理员",
			"sortable": False,
			"search": False,
			'width': 100
		},

		'manager_phone': {
			"label": u"管理员手机号",
			"sortable": False,
			"search": False,
			'width': 100
		},

		# 'manager_id_card_no': {
		# 	"label": u"管理员身份证",
		# 	"sortable": False,
		# 	"hidden": True,
		# 	'width': 100
		# },
		#
		# 'manager_id_card_img': {
		# 	"label": u"管理员身份证图片",
		# 	"hidden": True,
		# 	"sortable": False,
		# 	'width': 100
		# },

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.enterprise.erpinfo', ])
def erpinfo(request):
	"""
	企业信息
	:param request:
	:return:
	"""
	grid = SmerpErpinfoGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/enterprise/erpinfo.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.erpinfo.list', ])
def erpinfo_list(request):
	grid = SmerpErpinfoGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.erpinfo.add', 'enterprise.erpinfo.edit', 'enterprise.erpinfo.del'])
def erpinfo_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpErpinfoGrid()
	if oper == 'edit':
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.erpinfo.detail', ])
def erpinfo_detail(request):
	"""
	企业详情
	:param request:
	:return:
	"""
	id = request.GET.get('id')

	smerperpinfo = SmerpErpinfo.objects.get(id=id)
	smerpaccount = smerperpinfo.smerpaccount

	# 企业信息
	erp_info = []
	for field in smerperpinfo._meta.fields:
		field_name = field.name

		field_value = getattr(smerperpinfo, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("id", "smerpaccount"):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		erp_info.append({"name": field_name, "label": label, "value": field_value})

	# 企业账号信息
	account = []
	for field in smerpaccount._meta.fields:
		field_name = field.name
		label = field.verbose_name
		field_value = getattr(smerpaccount, field.name)
		if field_value is None:
			field_value = ""

		# 标签
		label = field.verbose_name
		if field.choices:
			print field.choices
			for item in field.choices:
				print item
				if field_value == item[0]:
					field_value = item[1]
					break

		account.append({"name": field_name, "label": label, "value": field_value})

	context = {
		"erp_info": erp_info,
		"account": account,
	}
	return render(request, "smAdmin/enterprise/erpinfo_detail.html", context=context)


def account_detail(request):
	"""
	企业的账号信息
	:param request:
	:return:
	"""
	id = request.GET.get('id')
	repinfo = SmerpErpinfo.objects.get(id=id)

	context = {
		"repinfo": repinfo,
	}
	return render(request, "smAdmin/enterprise/account_detail.html", context=context)


# -------------品牌列表------------------
class SmerpBrandGrid(JqGrid):
	model = SmerpBrand  # could also be a queryset
	pager_id = "brand-grid-pager"
	fields = ['id',
			  'name_zh',
			  'logo',
			  'check_status',
			  'smerpaccount__smerperpinfo__full_name',
			  'name_en',
			  # 'license_img',
			  # 'description',
			  'create_time',
			  'myac'
			  ]  # optional
	url = '/smAdmin/enterprise/brand_list'
	editurl = '/smAdmin/enterprise/brand_edit'
	caption = u'品牌列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'create_time': {
			"label": u"创建时间",

			'editable': False,
			"edittype": 'text',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			"hidden": True,
			'width': 100
		},
		'smerpaccount__smerperpinfo__full_name': {
			"label": u"所属企业",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			"editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},
		'name_zh': {
			"label": u"品牌名称",
			"sortable": False,

			"editable": True,
			"edittype": 'text',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'width': 100
		},
		'name_en': {
			"label": u"英文名称",
			"sortable": False,
			"sorttype": 'string',

			"editable": True,
			"edittype": 'text',

			"search": False,
			"stype": "text",

			"hidden": True,
			'width': 100
		},
		'check_status': {
			"label": u"审核状态",

			"sortable": False,
			"sorttype": 'integer',

			"editable": True,
			"edittype": 'select',
			"editoptions": {"value": "0:未提交;1:待审核;2:通过;3:驳回"},

			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "0:未提交;1:待审核;2:通过;3:驳回"},

			'width': 100
		},
		'logo': {
			"label": u"商标Logo",
			"sortable": False,

			"search": False,

			"hidden": False,
			'width': 100
		},
		'licence_img': {
			"label": u"商标注册证书",
			"sortable": False,

			"search": False,

			"hidden": True,
			'width': 100
		},

		'description': {
			"label": u"备注",
			"sortable": False,

			"search": False,

			"hidden": True,
			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.enterprise.brand', ])
def brand(request):
	"""
	品牌信息
	:param request:
	:return:
	"""
	grid = SmerpBrandGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/enterprise/brand.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.brand.list', ])
def brand_list(request):
	grid = SmerpBrandGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.brand.add', 'enterprise.brand.edit', 'enterprise.brand.del'])
def brand_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpBrandGrid()
	user = get_user(request)
	if oper == 'edit':
		if not user.has_perm('enterprise.brand.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('enterprise.brand.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('enterprise.brand.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.brand.detail', ])
def brand_detail(request):
	id = request.GET.get('id')

	smerpbrand = SmerpBrand.objects.get(id=id)

	# 品牌信息
	brand_info = []
	for field in smerpbrand._meta.fields:
		field_name = field.name

		field_value = getattr(smerpbrand, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("smerpaccount",):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		brand_info.append({"name": field_name, "label": label, "value": field_value})

	brand_licenses = []
	for item in smerpbrand.smerpbrandlicenses.all():
		brand_licenses.append([item.name, item.img])

	products = []
	for item in smerpbrand.smerpproducts.all():
		check_status_str = ""
		for c in CHECK_STATUS_CHOICES:
			if item.check_status == c[0]:
				check_status_str = c[1]
				break

		products.append([item.name, check_status_str, item.create_time])

	context = {
		"brand_info": brand_info,
		"brand_licenses": brand_licenses,
		"products": products,
	}
	return render(request, "smAdmin/enterprise/brand_detail.html", context=context)


# -------------产品列表------------------
class SmerpProductGrid(JqGrid):
	model = SmerpProduct  # could also be a queryset
	fields = ['id',
			  'name',
			  'check_status',
			  'smerpbrand__name_zh',
			  'smerpaccount__smerperpinfo__full_name',
			  'create_time',
			  'myac'
			  ]  # optional
	url = '/smAdmin/enterprise/product_list'
	editurl = '/smAdmin/enterprise/product_edit'
	caption = u'产品列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'name': {
			"label": u"产品名称",
			"sortable": False,
			'width': 100
		},
		'smerpbrand__name_zh': {
			"label": u"所属品牌",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},
		'smerpaccount__smerperpinfo__full_name': {
			"label": u"所属企业",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			"editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},

		'check_status': {
			"label": u"审核状态",
			"sortable": False,
			'width': 100
		},
		'create_time': {
			"label": u"创建时间",
			'editable': False,
			"hidden": True,
			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.enterprise.product', ])
def product(request):
	"""
	产品信息
	:param request:
	:return:
	"""
	grid = SmerpProductGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/enterprise/product.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.product.list', ])
def product_list(request):
	grid = SmerpProductGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.product.add', 'enterprise.product.edit', 'enterprise.product.del'])
def product_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpProductGrid()
	user = get_user(request)
	if oper == 'edit':
		if not user.has_perm('enterprise.product.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('enterprise.product.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('enterprise.product.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.product.detail', ])
def product_detail(request):
	id = request.GET.get('id')

	smerpprduct = SmerpProduct.objects.get(id=id)

	# 产品信息
	product_info = []
	for field in smerpprduct._meta.fields:
		field_name = field.name

		field_value = getattr(smerpprduct, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("smerpaccount", "smerpbrand", "smerpmaterials"):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		product_info.append({"name": field_name, "label": label, "value": field_value})

	# 证书
	product_licenses = []
	for item in smerpprduct.smerpproductlicenses.all():
		product_licenses.append([item.name, item.img])

	# 产品图片
	product_imgs = []
	for item in smerpprduct.smerpproductimgs.all():
		product_imgs.append([item.img, item.create_time])

	# 原料
	materials = []
	for item in smerpprduct.smerpmaterials.all():
		materials.append([item.name, item.producer, item.source_type, item.ref_image, item.ref_url])

	# 已购买的溯码记录
	smcode_logs = []
	for item in smerpprduct.smerpsmcodes.all():
		smcode_logs.append([item.create_time, item.num, item.start_no, item.end_no, item.publish_num, item.publish_end_no])

	# 发布记录
	publish_smcode_logs = []
	for item in smerpprduct.smerppublishsmcodelogs.all():
		publish_smcode_logs.append([item.create_time, item.pr, item.price, item.num, item.start_no, item.end_no])

	context = {
		"product_info": product_info,
		"product_licenses": product_licenses,
		"product_imgs": product_imgs,
		"materials": materials,
		"smcode_logs": smcode_logs,
		"publish_smcode_logs": publish_smcode_logs,
	}
	return render(request, "smAdmin/enterprise/product_detail.html", context=context)


# -------------原料列表------------------
class SmerpMaterialGrid(JqGrid):
	model = SmerpMaterial  # could also be a queryset
	pager_id = "material-grid-pager"
	fields = ['id',
			  'name',
			  'producer',
			  'source_type',
			  'ref_image',
			  'ref_url',
			  'smerpaccount__smerperpinfo__full_name',
			  'create_time',
			  'myac'
			  ]  # optional
	url = '/smAdmin/enterprise/material_list'
	editurl = '/smAdmin/enterprise/material_edit'
	caption = u'原料列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'name': {
			"label": u"名称",
			"sortable": False,
			'width': 150
		},
		'producer': {
			"label": u"产地",
			"sortable": False,
			'width': 100
		},
		'source_type': {
			"label": u"来源",
			"sortable": False,
			'width': 100
		},
		'ref_image': {
			"label": u"参考图片",
			"sortable": False,

			"hidden": True,
			'width': 100
		},
		'ref_url': {
			"label": u"参考资料",
			"sortable": False,

			"hidden": True,
			'width': 100
		},

		'smerpaccount__smerperpinfo__full_name': {
			"label": u"所属企业",

			"sortable": False,
			"sorttype": 'string',

			"editable": False,
			"edittype": 'text',
			"editoptions": {"size": "20", "maxlength": "40"},

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'width': 100
		},

		'create_time': {
			"label": u"创建时间",
			'editable': False,

			"hidden": True,
			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.enterprise.material', ])
def material(request):
	"""
	产品信息
	:param request:
	:return:
	"""
	grid = SmerpMaterialGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/enterprise/material.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.material.list', ])
def material_list(request):
	grid = SmerpMaterialGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.material.add', 'enterprise.material.edit', 'enterprise.material.del'])
def material_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpMaterialGrid()
	user = get_user(request)

	if oper == 'edit':
		if not user.has_perm('enterprise.material.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('enterprise.material.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('enterprise.material.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.material.detail', ])
def material_detail(request):
	id = request.GET.get('id')

	smerpmaterial = SmerpMaterial.objects.get(id=id)

	# 原料信息
	material_info = []
	for field in smerpmaterial._meta.fields:
		field_name = field.name

		field_value = getattr(smerpmaterial, field.name)
		if field_value is None:
			field_value = ""
		if field_name in ("smerpaccount",):
			continue

		# 标签
		label = field.verbose_name
		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break

		material_info.append({"name": field_name, "label": label, "value": field_value})

	context = {
		"material_info": material_info,
	}
	return render(request, "smAdmin/enterprise/material_detail.html", context=context)


# ------------- 订单列表 ------------------
class SmerpSmcodeOrderGrid(JqGrid):
	model = SmerpSmcodeOrder  # could also be a queryset
	pager_id = "order-grid-pager"
	fields = ['id',
			  'create_time',
			  'smerpproduct__name',
			  'num',
			  'pay_status',
			  'pay_time',
			  'add_code_status',
			  'order_id',
			  'myac'
			  ]  # optional
	url = '/smAdmin/enterprise/order_list'
	editurl = '/smAdmin/enterprise/order_edit'
	caption = u'订单列表'  # optional
	colmodel_overrides = {  # optional
		'id': {'key': True, 'width': 20, "hidden": True},
		'create_time': {
			"label": u"创建时间",
			"sortable": True,
			"sorttype": 'date',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			'width': 100
		},

		'smerpproduct__name': {
			"label": u"产品",
			"sortable": False,
			"sorttype": 'string',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'editable': False,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'num': {
			"label": u"数量",
			"sortable": False,
			"sorttype": 'string',

			"search": False,
			"stype": "text",
			"searchoptions": {"sopt": ['cn', ]},

			'editable': False,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'pay_status': {
			"label": u"付款状态",
			"sortable": True,
			"sorttype": 'string',

			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ]},

			'editable': False,
			"edittype": 'select',
			"editoptions": {"value": "0:未付款;1:处理中;2:已付款;"},

			'width': 100
		},

		'pay_time': {
			"label": u"付款时间",
			"sortable": False,
			"sorttype": 'date',

			"search": False,
			"stype": "text",
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			'width': 100
		},

		'add_code_status': {
			"label": u"增加溯码状态",
			"sortable": False,
			"sorttype": 'string',

			"search": False,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ]},

			'editable': False,
			"edittype": 'select',
			"editoptions": {"value": "0:未添加;1:处理中;2:已添加;"},

			'width': 100
		},

		'order_id': {
			"label": u"订单号",
			"sortable": False,
			"sorttype": 'string',

			"search": True,
			"stype": "text",
			"searchoptions": {"sopt": ['eq', ]},

			'editable': False,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.enterprise.order', ])
def order(request):
	"""
	产品信息
	:param request:
	:return:
	"""
	grid = SmerpSmcodeOrderGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/enterprise/order.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.order.list', ])
def order_list(request):
	grid = SmerpSmcodeOrderGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.order.add', 'enterprise.order.edit', 'enterprise.order.del'])
def order_edit(request):
	oper = request.POST.get('oper')
	id = request.POST.get('id')

	grid = SmerpSmcodeOrderGrid()
	user = get_user(request)

	if oper == 'edit':
		if not user.has_perm('enterprise.order.edit'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm('enterprise.order.add'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm('enterprise.order.del'):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.order.detail', ])
def order_detail(request):
	id = request.GET.get('id')

	smerporder = SmerpSmcodeOrder.objects.get(id=id)

	# 原料信息
	order_info = []
	for field in smerporder._meta.fields:
		field_name = field.name

		# if field_name in ("smerpaccount",):
		# 	continue
		# 标签
		label = field.verbose_name
		field_value = getattr(smerporder, field.name)
		if field_value is None:
			field_value = ""
		elif field_name == "smerpaccount":
			field_value = smerporder.smerpaccount.smerperpinfo.full_name;
		elif field_name == "smerpproduct":
			field_value = smerporder.smerpproduct.name

		if field.choices:
			for item in field.choices:
				if field_value == item[0]:
					field_value = item[1]
					break
		order_info.append({"name": field_name, "label": label, "value": field_value})

	is_not_pay = True
	if smerporder.pay_status == 2:
		is_not_pay = False

	context = {
		"order_info": order_info,
		"is_not_pay": is_not_pay
	}
	return render(request, "smAdmin/enterprise/order_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['enterprise.order.detail', ])
def order_pay_ok(request):
	try:
		id = request.GET.get('id')
		smerporder = SmerpSmcodeOrder.objects.get(id=id)

		if smerporder.pay_status == 2:
			ret = {"result": 0, "reason": u"该订单已经付款"}
			return HttpResponse(json.dumps(ret), content_type="application/json")

		# 确认对应的订单是否已经增加了溯源吗
		if SmerpSmcode.objects.get(smerpsmcodeorder=smerporder):
			ret = {"result": -1, "reason": u"该订单已经付款"}

			# 改变订单状态
			smerporder.pay_status = 2
			smerporder.add_code_status = 2
			smerporder.save()
			return HttpResponse(json.dumps(ret), content_type="application/json")

		order_id = smerporder.order_id
		product = smerporder.smerpproduct
		account = product.smerpaccount
		account_id = account.id
		product_id = product.id

		# 给产品增加溯码数量
		if smerporder.num > 0:
			start_no = 1
			pre_smcode = SmerpSmcode.objects.filter(smerpproduct=product).order_by("-end_no").first()
			if pre_smcode:
				start_no = pre_smcode.end_no + 1

			end_no = start_no + smerporder.num - 1
			my_smcode = SmerpSmcode(smerpsmcodeorder=smerporder, smerpaccount=account, smerpproduct=product, num=smerporder.num, start_no=start_no, end_no=end_no, publish_num=0, publish_end_no=0, create_time=datetime.now())
			my_smcode.save()

		# 改变订单状态
		smerporder.pay_status = 2
		smerporder.add_code_status = 2
		smerporder.save()

		ret = {"result": 0, "reason": u"确定付款成功"}
		return HttpResponse(json.dumps(ret), content_type="application/json")
	except:
		logger.exception("")

	ret = {"result": -1, "reason": u"系统异常"}
	return HttpResponse(json.dumps(ret), content_type="application/json")
